<?php
namespace app\api\controller;
use think\Controller;
use think\Config;
use think\Validate;
use think\Cache;
use think\Db;

class Game extends Controller{
    //刮刮乐及夺宝奇兵（大转盘）功能
    //夺宝奇兵(大转盘)
    public function bigTurntable(){
        //中奖记录广播
        $type = 0;
        $broadcast_list = $this->winningRecordBroadcast($type);
        //奖品列表
        $prize_list = db('games_prize')->field('prize_id,name,img,stock,prize_type,url,provide,desc')
                                       ->where("type = 0")
                                       ->select();
        foreach($prize_list as $k=>$v){
            if(!Validate::is($v['img'],'url')){
                $prize_list[$k]['img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$v['img'];
            }
        }
        //活动规则
        $activity_rules = db('config')->where("name = 'treasure'")->value('value');
        //宝贝推荐
        $page = input('post.page');
        if($page){
            if(!is_numeric($page)){return json_encode(array('code'=>401,'msg'=>'page参数类型有误'));}
         }else{
            $page = 0;
         }
        $goods_list = db('goods')->field('goods_id,name,mode,thumbnail_img,small,sale_type')
                                 ->where("shelves = 1 AND recommend = 1")
                                 ->order(['sort desc','goods_id'])
                                 ->limit($page*4,4)
                                 ->select();
        foreach($goods_list as $g=>$vo){
              $goods_list[$g]['price'] = $vo['small'];
              unset($goods_list[$g]['small']);
              if(!Validate::is($vo['thumbnail_img'],'url')){
                  $goods_list[$g]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$vo['thumbnail_img'];
              }
        }
        return json_encode(['code'=>200,'msg'=>'请求数据成功','broadcast_list'=>$broadcast_list,'prize_list'=>$prize_list,'activity_rules'=>$activity_rules,'goods_list'=>$goods_list]);
    }

    //夺宝奇兵  刮刮乐(中奖记录)
    public function WinningRecord(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $type = input('post.type');//0夺宝奇兵 1刮刮乐
        if(!is_numeric($type)){
            return json_encode(['code'=>401,'msg'=>'type类型错误']);
        }
        $page = input('post.page');
        if($page){
            if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page类型有误']);}
        }else{$page = 0;}
        $cache_name = 'user_id'.$user_id.'_type'.$type.'_page'.$page;
        if(cache($cache_name)){
            $record = cache($cache_name);
        }else{
            $record = db('winning_record')->field('record_id,prize_id,create_time')
                                          ->where("user_id = {$user_id} AND type = {$type} AND state != 3")
                                          ->order('create_time desc')
                                          ->limit($page*10,10)
                                          ->select();
            foreach($record as $key=>$value){
               $record[$key]['prize_name'] = db('games_prize')->where("prize_id = {$value['prize_id']}")->value('name');
               unset($record[$key]['prize_id']); 
               $record[$key]['create_time'] = date('Y-m-d H:i',$value['create_time']);
            }
        }
        if($record){
            Cache::tag('prizeRecord')->set($cache_name,$record,30);
            return json_encode(['code'=>200,'msg'=>'请求成功','record'=>$record]);
        }else{
            return json_encode(['code'=>201,'msg'=>'暂无数据']);
        }
    }

    ////中奖记录广播
    public function winningRecordBroadcast($type){
        $broadcast_list = db('winning_record')->field('user_id,prize_id')
                                              ->where("type = {$type} AND state != 3")
                                              ->order("create_time desc")
                                              ->limit(15)
                                              ->select();
        foreach($broadcast_list as $key=>$value){
            $broadcast_list[$key]['img'] = db('user')->where("user_id = {$value['user_id']}")->value('img');
            unset($broadcast_list[$key]['user_id']);
            $broadcast_list[$key]['prize_name'] = db('games_prize')->where("prize_id = {$value['prize_id']}")->value('name');
            unset($broadcast_list[$key]['prize_id']);
        }
        return $broadcast_list;
    }

    //刮刮乐
    public function scratch(){
        //中奖记录广播
        $type = 1;
        $broadcast_list = $this->winningRecordBroadcast($type);
        //活动规则
        $activity_rules = db('config')->where("name = 'scraping'")->value('value');
        return json_encode(['code'=>200,'msg'=>'请求数据成功','broadcast_list'=>$broadcast_list,'activity_rules'=>$activity_rules]);
    }

    //分享 分享到朋友圈可额外增加一次, 每日最多增加2次
    public function shareToCircle(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $type = input('post.type');//0夺宝奇兵 1刮刮乐
        if(!is_numeric($type)){return json_encode(['code'=>401,'msg'=>'type类型错误']);}
        if($type != 0 && $type != 1){return json_encode(['code'=>401,'msg'=>'type取值错误']);}
        $map = "user_id = {$user_id}";
        if($type == 0){
            $share_times = db('user')->where($map)->value('treasure_forward');
        }elseif($type == 1){
            $share_times = db('user')->where($map)->value('scraping_forward');
        }
        if($share_times >= 2){return json_encode(['code'=>402,'msg'=>'您今日分享到微信朋友圈获得额外抽奖次数已至2次上限']);}
        Db::startTrans();
        try{
          if($type == 0){
             db('user')->where($map)->setInc('treasure_forward');//转发次数
             db('user')->where($map)->setInc('treasure_frequency');//抽奖次数
          }elseif($type == 1){
             db('user')->where($map)->setInc('scraping_forward');
             db('user')->where($map)->setInc('scraping_frequency');
          }
          Db::commit();
        }catch(\Exception $e){
          Db::rollback();
          return json_encode(['code'=>201,'msg'=>'分享失败']);
        }
        return json_encode(['code'=>200,'msg'=>'分享成功,抽奖次数+1']);
    }

    //抽奖  抽中奖品
    public function lottery(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $type = input('post.type');//0夺宝奇兵 1刮刮乐
        if(!is_numeric($type)){return json_encode(['code'=>401,'msg'=>'type类型错误']);}
        if($type != 0 && $type != 1){return json_encode(['code'=>401,'msg'=>'type取值错误']);}
        $map = "user_id = {$user_id}";
        if($type == 0){
            $draws_number = db('user')->where($map)->value('treasure_frequency');
        }elseif($type == 1){
            $draws_number = db('user')->where($map)->value('scraping_frequency');
        }
        if($draws_number == 0){return json_encode(['code'=>402,'msg'=>'您今日可抽奖次数已用完!']);}//接数据时关闭，记得打开
        $where = "type = {$type}";
        $prize_list = db('games_prize')->field('prize_id,chance')->where($where)->select();
        $arr = [];
        foreach($prize_list as $key=>$value){
           $arr[$value['prize_id']] = $value['chance'];
        }
        $prize_id = getRand($arr);//抽中的奖项id
        // if($type == 0){$field = 'prize_id,stock,prize_type,url,provide,desc';}
        // elseif($type == 1){$field = 'prize_id,name,img,stock,prize_type,url,provide,desc';}
        $field = 'prize_id,name,img,stock,prize_type,url,provide,desc';
        $str = "prize_id = {$prize_id}";
        $prize_info = db('games_prize')->field($field)->where($str)->find();
        if(isset($prize_info['img'])){$prize_info['img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$prize_info['img'];}
        //中奖记录
        $recordData = [];
        $recordData['user_id'] = $user_id;
        $recordData['prize_id'] = $prize_id;
        $recordData['create_time'] = time();
        if($type == 1){
           $recordData['type'] = 1;
        }
        if($prize_info['prize_type'] == 3){
           $recordData['state'] = 3;
        }
        //奖品库存>0
        if($prize_info['stock'] > 0){
            Db::startTrans();
            try{
               db('games_prize')->where($str)->setDec('stock');//减去奖品库存
               //减去抽奖次数
               if($type == 0){
                   db('user')->where($map)->setDec('treasure_frequency');
                   $recordData['type'] = 0;
               }elseif($type == 1){
                   db('user')->where($map)->setDec('scraping_frequency');
                   $recordData['type'] = 1;
               }
               //添加中奖记录
               $record_id = db('winning_record')->insertGetId($recordData);
               Db::commit();
            }catch(\Exception $e){
               Db::rollback();
               return json_encode(['code'=>201,'msg'=>'抽奖失败']);
            }   
            return json_encode(['code'=>200,'msg'=>'抽奖成功','prize_info'=>$prize_info,'record_id'=>$record_id]);
        }else{
            $recordData['state'] = 2;
            db('winning_record')->insert($recordData);
            return json_encode(['code'=>200,'msg'=>'奖品已发完,谢谢参与!','prize_info'=>$prize_info]);
        }
                                   
    }

    //领奖 (领取奖品)  手动发放（后台客服手动发放奖品）
    //虚拟奖品手动发放。不用配置
    //实物奖品手动发放，就是要填写收货地址。
    //点击立即领取后 提示 “稍后客服人员会自动将奖品发放到您的账户”
    public function receivePrize(){
        $record_id = input('post.record_id');
        if(!is_numeric($record_id)){return json_encode(['code'=>401,'msg'=>'record_id参数类型错误']);}
        $map = "record_id = {$record_id}";
        $record_info = db('winning_record')->field('prize_id')->where($map)->find();
        $where = "prize_id = {$record_info['prize_id']}";
        $prize_info = db('games_prize')->field('stock,prize_type,provide')->where($where)->find();
        if($prize_info['prize_type'] == 0){return json_encode(['code'=>402,'msg'=>'prize_type类型错误']);}
        //provide 0不需要提供地址;1需要提供地址;
        $updateData = [];
        $updateData['receive_time'] = time();
        // $updateData['state'] = 0;//虚拟奖品手动发放、实物奖品手动发放 这2种奖品都需要后台进行操作,手动发放奖品;
        if($prize_info['provide'] == 1){
            $updateData['receiver'] = input('post.receiver');
            if($updateData['receiver'] == '' || $updateData['receiver'] == 'null' || $updateData['receiver'] == 'undefined'){
                return json_encode(['code'=>401,'msg'=>'收货人参数缺失']);
            }
            $updateData['phone'] = input('post.phone');
            if($updateData['phone'] == '' || $updateData['phone'] == 'null' || $updateData['phone'] == 'undefined'){
                return json_encode(['code'=>401,'msg'=>'联系电话参数缺失']);
            }
            $updateData['area'] = input('post.area');
            $updateData['street'] = input('post.street');
            $updateData['address'] = input('post.address');
            if($updateData['address'] == '' || $updateData['address'] == 'null' || $updateData['address'] == 'undefined'){
                return json_encode(['code'=>401,'msg'=>'详细地址参数缺失']);
            }
        }
        Db::startTrans();
        try{
           // db('games_prize')->where($where)->setInc('receive_number');//奖品领取数+1
           db('winning_record')->where($map)->update($updateData);
           Db::commit();
        }catch(\Exception $e){
           Db::rollback();
           return json_encode(['code'=>201,'msg'=>'领奖失败']);
        }
        return json_encode(['code'=>200,'msg'=>'领奖成功,稍后客服人员会自动将奖品发放到您的账户']);                                     
    }

    //虚拟奖品自动领奖  虚拟奖品自动兑奖，就是通过接口链接到优惠券，点击后，直接给用户增加上优惠券
    public function automaticCollection(){
        $record_id = input('post.record_id');//中奖id
        if(!is_numeric($record_id)){return json_encode(['code'=>401,'msg'=>'record_id参数类型错误']);}
        $coupons_id = input('post.coupons_id');
        if(!is_numeric($coupons_id)){return json_encode(['code'=>401,'msg'=>'coupons_id参数类型错误']);}
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $map = "record_id = {$record_id}";
        $record_info = db('winning_record')->field('prize_id')->where($map)->find();
        $where = "prize_id = {$record_info['prize_id']}";
        $prize_info = db('games_prize')->field('prize_type')->where($where)->find();
        if($prize_info['prize_type'] != 0){return json_encode(['code'=>402,'msg'=>'prize_type类型错误']);} 
        //provide 0不需要提供地址;1需要提供地址;
        $updateData = [];
        $updateData['receive_time'] = time();
        $updateData['state'] = 0;
        $addCoupons = [];
        $addCoupons['coupons_id'] = $coupons_id;
        $addCoupons['user_id'] = $user_id;
        $addCoupons['receive_time'] = time();
        $addCoupons['state'] = 0;
        Db::startTrans();
        try{
           db('games_prize')->where($where)->setInc('receive_number');//奖品领取数+1
           db('winning_record')->where($map)->update($updateData);
           db('coupons_use')->insert($addCoupons);//虚拟奖品自动发放 添加优惠券到用户
           Db::commit();
        }catch(\Exception $e){
           Db::rollback();
           return json_encode(['code'=>201,'msg'=>'领奖失败']);
        }
        return json_encode(['code'=>200,'msg'=>'领奖成功']);    
    }
    
}